package com.crud.controller;

import com.crud.pojo.Employee;
import com.crud.pojo.Msg;
import com.crud.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Author sc
 * @ClassName EmployeeController  处理员工增删改查
 * @Description class function:
 * @Date 2022/4/6 15:08:54
 **/


@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

//    @DeleteMapping("/emps/{id}")
//    @ResponseBody
//    public Msg deleteEmp(@PathVariable("id") Integer id) {
//        employeeService.deleteEmp(id);
//        return Msg.success();
//    }

    /**
     * 单个批量二合一
     * 批量删除：1-2-3
     * 单个删除：1
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/emps/{ids}",method=RequestMethod.DELETE)
    public Msg deleteEmp(@PathVariable("ids")String ids){
        //批量删除
        if(ids.contains("-")){
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            //组装id的集合
            for (String string : str_ids) {
                del_ids.add(Integer.parseInt(string));
            }
            employeeService.deleteBatch(del_ids);
        }else{
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }

    @RequestMapping("/checkuse")
    @ResponseBody
    public Msg checkuuse(@RequestParam("empName") String empName) {
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u4e00-\\u9fa5]{2,5})";

        if (!empName.matches(regx)) {
            return Msg.fail().add("va_msg", "用户名必须是6-16位字母和数字的组合或者2-5位中文");
        }
        boolean b = employeeService.chrckUser(empName);
        if (b) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "用户名不可用");
        }
    }

    /**
     * 通过json交互
     *
     * @param pn
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsithJson(
            @RequestParam(value = "pn", defaultValue = "1") Integer pn) {
//        引入pageHelper插件
        PageHelper.startPage(pn, 5);
//            startPage后面紧跟的查询语句是一个分页查询
        List<Employee> emps = employeeService.getll(0);
//        将查询结果封闭在pageinfo,,连续显示5页
        PageInfo page = new PageInfo(emps, 5);
        return Msg.success().add("pageInfo", page);

    }

    /**
     * 员工保存
     *
     * @return
     */
    @RequestMapping(value = "/emps", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Validated Employee employee, BindingResult result) {
        if (result.hasErrors()) {

            Map<String, Object> map = new HashMap<>();
//            校验失败
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError error : errors) {
                System.out.println("错误的字段名:" + error.getField());
                System.out.println("错误信息:" + error.getDefaultMessage());
                map.put(error.getField(), error.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        } else {
            employeeService.saveEmp(employee);
            return Msg.success();
        }
    }

    @RequestMapping(value = "/emps/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable("id") Integer id) {
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp", employee);
    }

    @PutMapping("/emps/{empId}")
    @ResponseBody
    public Msg update(Employee employee) {
        System.out.println(employee);
        employeeService.updateEmp(employee);
        return Msg.success();
    }

    //    返回pageInfo
//    @RequestMapping("/emps")
    public String list(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
//        引入pageHelper插件
        PageHelper.startPage(pn, 5);
//        startPage后面紧跟的查询语句是一个分页查询
        List<Employee> emps = employeeService.getll(0);
//        将查询结果封闭在pageinfo,,连续显示5页
        PageInfo page = new PageInfo(emps, 5);
        model.addAttribute("pageInfo", page);
        return "list";
    }


}
